<?php
/**
 * 空控制器
 */
namespace app\service\controller;
use think\controller\Rest;
class User extends Rest{
    protected $header = [];
    protected $error_info = '';
    protected $user_info = [];
     /**
     * 架构函数 取得模板对象实例
     * @access public
     */
    public function __construct()
    {
        parent::__construct();
        $this->mod = model('open/User');
    }
    /**
	 * 字符串替换方法
	 */
	protected function _replace($str = '', $reg = '', $replace = '_') {
		$leng = strlen($str);
		for ($i = 0; $i < $leng; $i++) {
			$char = substr($str, $i, 1);
			if (preg_match($reg, $char)) {
				$str = str_replace($char, $replace . strtolower($char), $str);
			}
		}
		return strtoupper($str);
	}
    /**
	 * @name 调用服务发送请求操作
	 * @param string $type 请求的类型   [post,put,get,delete]
	 * @param array $params 请求时携带的参数
	 * @param string $url  请求的url
	 * @return array 请求后的返回数据
	 */
	protected function request($type = '', $params = [], $url = '') {
		if (!$type || !$url) {
			return [];
		}

		//加载httpful
		vendor('Bootstrap', VENDOR_PATH . 'Httpful' . DS);
		//初始化
		\Httpful\Bootstrap::init();
		//参数拼接
		if (in_array($type, ['get', 'delete'])) {
			$url .= '?' . http_build_query($params);
			$send = \Httpful\Request::$type($url);
		} else {
			$send = \Httpful\Request::$type($url)
				->sendsForm()
				->body($params);
		}
		foreach ($this->header as $key => $val) {
			$send = $send->$key($val);
		}
		$response = $send
			->expectsHtml()
			->send();
		//数据转换为数组返回
		return $response->body;
	}
	/**
     	* 删除回放(本地)
     	* @Author   Wayne
     	* @DateTime 2018-01-04
     	* @Email    qiaobin@zhiyicx.com
     	* @return   [Boolean]              [删除结果]
     	*/
    	public function deleteVideo () {
       	 	//检测授权
        	if(!$this->checkAuth()){
            		// 授权没有通过
            		return $this->response(['code'=>0,'message'=>$this->error_info], 'json', 401);
        	}
        	$res = model('stream/Video')->delete(decrypt_id($_GET['vid']));
        	return true;
    	}
	
	/**
     	* [getOneVideo 获取一个回放视频，用于回放同步到第三方]
     	* @Author   Wayne
     	* @DateTime 2018-01-11
     	* @Email    qiaobin@zhiyicx.com
     	* @return   [boolean]
     	*/
    	public function getOneVideo()
    	{	
		$vid = intval($_GET['vid']);
        	// 检测授权
        	if (!$this->checkAuth() || !$vid) {
            		return $this->response(['code' => 0, 'message' => $this->error_info], 'json', 401);
        	}
        	$where['vid'] = $vid;
        	$video = model('stream/Video')->getOne($where);
		if (!$video) {
            		return $this->response(['code' => 0, 'message' => '未找到回放视频'], 'json', 404);
        	}
        	if (is_numeric($video['video_icon'])) {
            		$video['video_icon'] = model('attach/Attach', ['getAttachUrl', $video['video_icon']])[0];
        	} else {
			$video['video_icon'] = C('qiniu.cdn-url') .'/' . $video['video_icon'];
		}
        	$video['source_id'] = (int) $video['vid'];
        	$video['vid'] = encrypt_id($video['vid']);
        	$video['shop'] = model('stream/StreamShop')->getInstance()->getShopByVideo($video['vid']);

        	return $this->response(['code' => 1, 'data' => $video], 'json', 200);
    	}
	
    /**
     * @name 获取并设置当前请的参数
     */
    protected function getParams(){
        switch ($this->_method){
            case 'get':
            case 'delete':
                $this->user_info = $_GET;
                break;
            default:
                $this->user_info = $_POST;
                break;
        }
        return $this->user_info;
    }
    public function user($usid = '')
    {
        $this->getParams();
        //检测授权
        if(!$this->checkAuth()){
            //授权没有通过
            return $this->response(['code'=>0,'message'=>$this->error_info], 'json', 401);
        }
        // 资源类型检测
        switch ($this->_method){
            case 'get':
                return $this->_get($usid);
                break;
            case 'post': 
                return $this->_add();
                break;
            case 'delete':
                return $this->_delete($usid);
                break;
        }
        return $this->response(['code'=>0,'message'=>'Unsupported request method type'], 'json', 501);
    }
    /**
     * @name 添加用户,存在则更新,ticket存在会更新授权
     */
    protected function _add(){
        $data = [
			'usid' => $this->user_info['usid'],
			'uname' => string_filter($this->user_info['uname']),
		];
		if(isset($this->user_info['sex'])){
			$data['sex'] = (int)$this->user_info['sex'] ?: 2;//1 男 2 女
		}
        isset($this->user_info['ticket']) && $data['ticket'] = true;
		//return $this->response($data,'json','200');
		$res = $this->mod->addUser($data);
		if ($res === false) {
            return $this->response(['code'=>0,'message'=>$this->mod->getError()], 'json', $this->mod->getHttpCode());
		} else {
		    $return = ['code' => 1,'data' => ['ticket' => $res]];
			return $this->response($return, 'json', 201);
		}
    }
    /**
     * @name 获取用户信息
     */
    protected function _get($usid = ''){
        if($usid){
            $uid = $this->mod->getUidByUsid($usid);
            $uid && $this->user_info = $this->mod->getUserInfo($uid);
            if($uid && $this->user_info){
                $return = ['code' => 1,'data' => (array)$this->user_info];
                return $this->response($return, 'json', 200); 
            }
        }
        return $this->response(['code' => 0,'message'=>'Not find user by usid for `'.$usid.'`'], 'json', 404);
    }
    /**
     * @name 删除一个用户
     */
    protected function _delete($usids){
        if($usids){
            if(!is_array($usids)){
                $usids = explode(',',$usids);
            }
            $usids = array_filter(array_unique($usids));
	    return $usids;
            $num = 0;
            $user = [];
            foreach($usids as $usid){
                $uid = $this->mod->getUidByUsid($usid);
                if($uid && $count = $this->mod->deleteUserByUid($uid)){
                    $num +=$count;
                    $user[] = $usid;
                }
            }
            if($num >0 ){
                $return = ['code' => 1,'data' => ['count'=>$num,'usid'=>$user]];
                return $this->response($return, 'json', 200);
            } 
        }
        return $this->response(['code' => 0,'message'=>'Not find user by usid for `'.implode(',',$usids).'`'], 'json', 404);
    }

    /**
     * 同步删除用户
     * @Author   Wayne
     * @DateTime 2018-01-26
     * @Email    qiaobin@zhiyicx.com
     * @return   [type]              [description]
     */
    public function deleteUser () {
        if (!$this->checkAuth()) {
            return $this->response(['code'=>0,'message'=>$this->error_info], 'json', 401);
        }
        $usid = $_GET['usid'];
	$uid = $this->mod->getUidByUsid($usid);
	if ($uid) {
	    if ($this->mod->deleteUserByUid($uid)) {
		return $this->response(['code' => 1], 'json', 200);
	    } else {
		return $this->response(['code' => 2], 'json', 200);
	    }
	} else {
		return $this->response(['code' => 0], 'json', 200);
	}
    }

    /**
     * @name 请求的授权票据参数不正确
     */
    public function ticketError(){
        return $this->response(['code' => 0,'message'=>'Not find user,please check params for ticket'], 'json', 400);
    }
    /**
     * @name 访问接口权限检测(仅在有配置才会生效)
     */
    protected function checkAuth(){
        //获取user服务器的配置
        $list = model('admin/Config')->getConfigList('user_service','user_service_api',1);
        $user_service = [];
        if($list['data'][0]){
            $config = $list['data'][0]['value'];
            foreach($config as $k=>$v){
                foreach($v as $name=>$value){
                    $user_service[$k][$name] = [
                        'value' => $value,
                        'type'  => 1
                    ];
                }
                
            }
        }
        if($user_service){
            $_header = $user_service['header'];
            if(is_array($_header)){
                foreach($_header as $_k => $_p){
                    $k = self::_replace($_k, '/^[A-Z]$/');
                    if($this->getEncryptStr($_p['type'],$_p['value']) !== strtolower($_SERVER['HTTP'.$k])){
                        $this->error_info = 'Your server is not accessible,because auth has error in header for '.$_k;
                        return false;
                    }
                }
            }
            $_body = $user_service['params'];
            if(is_array($_body)){
                foreach($_body as $_k => $_p){
                    if($this->getEncryptStr($_p['type'],$_p['value'],false) != $this->user_info[$_k]){
                        $this->error_info = 'Your server is not accessible,because auth has error in params for '.$_k;
                        return false;
                    }
                }
            }                                                                                                                                                                                                                        
        }
        return true;
    }
    /**
     * @name 处理取得各种方式加密后的字符串
     * 1：deault 2：sha1  3：base64 4:md5
     */
    protected function getEncryptStr(int $type , string $string, $tolower = true){
        switch($type){
            case 2:
                $string = sha1($string);
                break;
            case 3:
                $string = base64_encode($string);
                break;
            case 4:
                $string = md5($string);
                break;
            default:
                break;
        }
        return $tolower === true ? strtolower($string) : $string;
    }
    /**
     * @name 客户服务器主动通知需要同步
     */
    public function syncNotify(){
        //处理参数
        $this->getParams();
        //检测授权
        if(!$this->checkAuth()){
            //授权没有通过
            return $this->response(['code'=>0,'message'=>$this->error_info], 'json', 401);
        }
        $usid = $this->user_info['usid'];
        $uid = model('open/User')->getUidByUsid($usid);
        if(!$uid){
            return $this->response(['code'=>0,'message'=>'Not find user by usid for `'.$usid.'`'], 'json', 404);
        }
        $res = model('open/UserData')->setSync($uid);
        if($res){
            $return = ['code' => 1,'data' => ['usid'=>$usid]];
            return $this->response($return, 'json', 200); 
        }
        $return = ['code' => 0,'message'=>'The service haddle error,please try again later'];
        return $this->response($return, 'json', 500); 
    }
 }
